﻿using AutoMapper;
using Basic.Traceability.Domain.DeepProcessing;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.DeepProcessing.DeepProcessingPackagingMaterials;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.DeepProcessing.DeepProcessingPackagingMaterials
{
    public class CreateDeepProcessingPackagingMaterialsHandler : IRequestHandler<CreateDeepProcessingPackagingMaterialsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DeepProcessingPackagingMaterialsModel> _packagingMaterialsRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateDeepProcessingPackagingMaterialsHandler> logger;

        public CreateDeepProcessingPackagingMaterialsHandler(IBaseRepository<DeepProcessingPackagingMaterialsModel> packagingMaterialsRepository, IMapper mapper, ILogger<CreateDeepProcessingPackagingMaterialsHandler> logger)
        {
            _packagingMaterialsRepository = packagingMaterialsRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加包装材料
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateDeepProcessingPackagingMaterialsCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<DeepProcessingPackagingMaterialsModel>(request);
            model.Id = YitIdHelper.NextId();
            var r = _packagingMaterialsRepository.Create(model);
            if (r > 0)
            {
                res.Msg = "添加包装材料成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                logger.LogInformation("创建成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "添加包装材料失败";
                res.Code = APIEnums.Fail;
                res.Data = r;
                logger.LogError("创建失败");
                return Task.FromResult(res);
            }
            
        }
    }
}
